/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hadss.adaptive_video

import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Build
import android.view.Display
import android.view.Surface
import android.view.WindowManager
import androidx.annotation.RequiresApi
import io.flutter.plugin.common.EventChannel

/**
 * 屏幕旋转监听事件
 */
class ScreenOrientationStreamHandler(
    private val activity: Activity,
    private val sensorManager: SensorManager,
    private var interval: Int = SensorManager.SENSOR_DELAY_NORMAL,
) :
    EventChannel.StreamHandler, SensorEventListener {
    private val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
    private var eventSink: EventChannel.EventSink? = null
    private val windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private val display: Display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        getDisplayApiR()
    } else {
        getDisplayApiL()
    }
    private var lastRotation: Int = -1

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        eventSink = events
        sensorManager.registerListener(this, sensor, interval)
    }

    override fun onCancel(arguments: Any?) {
        sensorManager.unregisterListener(this)
        eventSink = null
    }

    override fun onSensorChanged(event: SensorEvent?) {
        screenOrientation()
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
    }

    fun setUpdateInterval(interval: Int) {
        this.interval = interval
        if (eventSink != null) {
            sensorManager.unregisterListener(this)
            sensorManager.registerListener(this, sensor, interval)
        }
    }

    private fun screenOrientation() {
        val rotation = when (display.rotation) {
            Surface.ROTATION_0 -> 0
            Surface.ROTATION_90 -> 1
            Surface.ROTATION_180 -> 0
            Surface.ROTATION_270 -> 1
            else -> 0
        }
        if (lastRotation != rotation) {
            lastRotation = rotation
            eventSink?.success(lastRotation)
        }
    }

    private fun getDisplayApiL(): Display {
        return windowManager.defaultDisplay
    }

    @RequiresApi(Build.VERSION_CODES.R)
    private fun getDisplayApiR(): Display {
        return activity.display!!
    }
}